package base

import (
	"os"
	"bufio"
	"strconv"
	"time"
)

/**
 * 判断文件是否存在  存在返回 true 不存在返回false
 */
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

var api_brief *os.File
var api_detail *os.File
var api_err *os.File

func openFile() {
	var filename = "../../logs/test/test.log"
	var filename2 = "../../logs/test/test_detail.log"
	var filename3 = "../../logs/test/test_err.log"
	var err error
	os.Mkdir("../../logs/test/",os.ModePerm)
	if checkFileIsExist(filename) { //如果文件存在
		api_brief, err = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
	} else {
		api_brief, err = os.Create(filename) //创建文件
	}
	if err != nil {
		panic(err)
	}

	if checkFileIsExist(filename2) { //如果文件存在
		api_detail, err = os.OpenFile(filename2, os.O_APPEND, 0666) //打开文件
	} else {
		api_detail, err = os.Create(filename2) //创建文件
	}
	if err != nil {
		panic(err)
	}

	if checkFileIsExist(filename3) { //如果文件存在
		api_err, err = os.OpenFile(filename3, os.O_APPEND, 0666) //打开文件
	} else {
		api_err, err = os.Create(filename3) //创建文件
	}
	if err != nil {
		panic(err)
	}
}

func APICheckAction(st int64, state int, url,param,result string) {
	t2,err := strconv.ParseFloat(strconv.FormatInt(time.Now().UnixNano() - st,10),10)
	t := "时间计算失败"
	if err == nil{
		t = strconv.FormatFloat(t2/1000000000, 'f', 2, 64)
	}

	w := bufio.NewWriter(api_brief)
	wstr := ""
	if state == 0 {
		wstr += "success \t"
	} else {
		wstr += "fail \t"
	}
	wstr += url + " \t"
	wstr += t + "s \t"
	wstr += "\n"
	w.WriteString(wstr)
	w.Flush()

	APITestDetail(url,param,result)
	if state != 0 {
		APITestError(url,param,result)
	}
}

func APITestDetail(url,param,result string) {
	w := bufio.NewWriter(api_detail)
	wstr := "*************************************************************************************************\n"
	wstr += "\n"
	wstr += "\turl:\t"+url+"\n"
	wstr += "\tparam:\t"+param+"\n"
	wstr += "\tresult:\t"+result+"\n"
	wstr += "\n"
	w.WriteString(wstr)
	w.Flush()
}

func APITestError(url,param,result string) {
	w := bufio.NewWriter(api_err)
	wstr := "*************************************************************************************************\n"
	wstr += "\n"
	wstr += "\turl:\t"+url+"\n"
	wstr += "\tparam:\t"+param+"\n"
	wstr += "\tresult:\t"+result+"\n"
	wstr += "\n"
	w.WriteString(wstr)
	w.Flush()
}

func init() {
	openFile()
}
